package com.example.librarymanagementsystembackend.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

public class JwtUtil {
    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); ; // 密钥需保密
    private static final long EXPIRATION_TIME = 86_400_000; // 1天

    public static String generateToken(String userId) {
        return Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY)
                .compact();
    }

//    public static boolean validateToken(String token, String userId) {
//        try {
//            String userId = Jwts.parser()
//                    .setSigningKey(SECRET_KEY)
//                    .parseClaimsJws(token)
//                    .getBody()
//                    .getSubject();
//            return userId.equals(userId) && !isTokenExpired(token);
//        } catch (Exception e) {
//            return false;
//        }
//    }

    public static String getValidTokenSubject(String token) {
        String userId = null;
        try {
            userId = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            if (!userId.equals(userId) || isTokenExpired(token)) {
                userId = null;
            }
        } catch (Exception e) {
            userId = null;
        }
        return userId;
    }

    private static boolean isTokenExpired(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody()
                .getExpiration()
                .before(new Date());
    }
}
